import { useEffect, useRef, useState } from 'react'
import UserLayout from '@c/user/user-layout'
import styles from './index.module.scss'
import Button from '@c/button'
import cm from 'classnames'
import ModalSuccess from '@c/modal/modal-active-success'
import { useShowLogin } from '@/utils/hooks'
import { useRecoilValue } from 'recoil'
import { userInfo } from '@/store'
import { codeConvert } from '@/api/home'
import { activeCodeReport } from '@/utils/report'

const Index = () => {
  const [code, setCode] = useState('')
  const [isFocus, setFocus] = useState(false)
  const [error,setError] = useState('')
  const inputRef = useRef(null)
  const [isSuccess, setSuccess] = useState(false)
  const login = useShowLogin()
  const [day,setDay] = useState(0)
  const user = useRecoilValue(userInfo)
  const focused = e => {
    e.stopPropagation()
    inputRef.current?.focus()
    setFocus(true)
  }
  const blured = () => {
    inputRef.current?.blur()
    setFocus(false)
  }

  const submit = async () => {
    const res = await codeConvert({ code })
    activeCodeReport({
      isSuccess:!res.code,
      'activation-plan': res?.data,
      'activation_error':res.msg 
    })
    if(res.code){
      setError(res.msg)
    }else{
      setError('')
      setSuccess(true) 
      setDay(res.data)
    }

  }

  const close = () => {
    setCode('')
    setSuccess(false)
  }

  useEffect(() => {
    window.addEventListener('click', blured)
    return () => {
      window.removeEventListener('click', blured)
      sessionStorage.setItem('lastPage', true)
    }
  }, [])

  const notLogin = <>
    <p className={cm(styles.title,styles.titleNotLogin)}>请登录后使用激活码~</p>
    <Button className={cm(styles.btn,styles.btnLogin)} hover="opacity" onClick={login}>登录</Button>
  </>

const formateInput = e => {
  const value = e.currentTarget.value.slice(0, 12)
  if (/^[0-9]*$/.test(value)) {
    setCode(value)
  }
}

  const isLogin = <>
     <p className={styles.title}>请输入激活码</p>
        <div className={styles.codeBox}>
          <div className={styles.span} onClick={focused}>
            {code.slice(0, 4)}
            <span className={cm(styles.cursor, isFocus && code.length < 4 ? styles.focus : '')}></span>
          </div>
          <div className={styles.span} onClick={focused}>
            {code.slice(4, 8)}
            <span className={cm(styles.cursor, isFocus && 4 <= code.length && code.length < 8 ? styles.focus : '')}></span>
          </div>
          <div className={styles.span} onClick={focused}>
            {code.slice(8, 12)}
            <span className={cm(styles.cursor, isFocus && 8 <= code.length && code.length < 12 ? styles.focus : '')}></span>
          </div>
          <input ref={inputRef} className={styles.input} onBlur={blured} value={code} onChange={formateInput} />
        </div>
        { error && <p className={styles.error}>{error}</p> }
        <Button className={styles.btn} hover="opacity" onClick={submit}>确认</Button>
  </>
  return (
    <UserLayout type="active-code">
      <div className={styles.activeCode}>
        { typeof user.token !== 'undefined'  ? user.token ? isLogin : notLogin : null }
      </div>
      {isSuccess && <ModalSuccess user={user} day={day} onClose={close} />}
    </UserLayout>
  )
}

export default Index

export async function getServerSideProps() {
  return {
    props: {
      layoutProps: {
        noSomeMetaInfo: false,
        url: '/active-code',
        title: '星视界 - 激活码兑换会员',
        desc: '星视界是一款海外华人电视直播和影视大全，免费观看中文电视节目和影视内容。在这里，您可以畅享中文直播内容及海量影视资源，涵盖香港、台湾、新马、大陆频道直播，以及电视剧、电影、综艺、动漫节目点播等，尽情享受视听盛宴。'
      }
    }
  }
}
